<template>
  <div class="mobile-frame">
    <div style="height: calc(100% - 54px)">
      <van-nav-bar>
        <template #title>
          <van-search label="叫料 " left-icon="" v-model="qrcode_str" placeholder="扫描单码" @search="onSearch" />
        </template>
        <template #right> </template>
      </van-nav-bar>
      <div style="width: 100%; height: calc(100% - 50px); overflow: auto">
        <div v-if="active === 0" style="padding-top: 10px">
          <van-cell-group inset>
            <van-field label="业务类型" v-model="qrdoc.type" />
            <van-field label="单号" v-model="qrdoc.order" />
            <van-field label="条码" v-model="qrdoc.qrcode" />
            <van-field @click="showPicker = true" label="叫料位置" v-model="qrdoc.loc" is-link readonly />
            <van-field @click="showDtPicker = true" label="需求日期" v-model="qrdoc.reqdate" is-link readonly />
          </van-cell-group>
          <div style="padding: 15px 15px 15px 15px">
            <van-list finished-text="没有更多了">
              <van-cell
                v-for="item in qrdoc.details"
                :key="item.billcode"
                :value="item.order_qty - item.called_qty"
                clickable
                is-link
                @click="add_item(item)"
              >
                <template #title>
                  <span style="margin-right: 5px">{{ typeof item.material === 'string' ? item.material : item.material.name }}</span>
                  <van-tag v-if="qrdoc.selected.map((r) => r.order).indexOf(item.billcode) >= 0" type="primary">已选中</van-tag>
                </template>
                <template #icon>
                  <van-icon name="add-o" />
                </template>
              </van-cell>
            </van-list>
          </div>
        </div>
        <div v-if="active === 1" style="padding-top: 10px">
          <div style="padding: 15px 15px 15px 15px">
            <van-list finished-text="没有更多了">
              <van-cell v-for="item in qrdoc.selected" :key="item.order" :title="item.order" :label="item.materialname">
                <template #value>
                  <van-stepper v-model="item.qty" min="0" />
                </template>
              </van-cell>
            </van-list>
          </div>
        </div>
        <div v-if="active === 2" style="padding-top: 10px; height: 100%">
          <div style="padding: 15px 15px 15px 15px; height: calc(100% - 50px)">
            <van-list finished-text="没有更多了">
              <van-cell
                v-for="item in sum_item()"
                :key="item.material"
                :title="item.material"
                :label="item.materialname"
                :value="item.qty"
              >
              </van-cell>
            </van-list>
          </div>
          <van-button type="primary" block @click="submit">提交</van-button>
        </div>
        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker title="送料点" :columns="[{ text: 'A区' }, { text: 'B区' }]" @confirm="locSelect" @cancel="showPicker = false" />
        </van-popup>
        <van-popup v-model:show="showDtPicker" round position="bottom">
          <van-date-picker v-model="currentDate" @confirm="reqDtSelect" @cancel="showDtPicker = false" title="选择日期" />
        </van-popup>
      </div>
    </div>

    <van-tabbar v-model="active" :fixed="false">
      <van-tabbar-item icon="search">备选</van-tabbar-item>
      <van-tabbar-item icon="list-switch">已选</van-tabbar-item>
      <van-tabbar-item icon="notes-o">汇总</van-tabbar-item>
    </van-tabbar>
  </div>
</template>
<script lang="ts" setup>
import { useDbStore } from '@/stores/modules/database'
import { ref } from 'vue'
import { showDialog } from 'vant'
import { fill_ref_info, get_code_prefix, make_billcode } from '@/utils/common'
import { e_code_prefix, e_require_order_status } from '@/types/enum'
import { require_order_define } from '@/meta'
import type { require_order } from '@/types/billdata'
import { require_to_mtlcall } from '@/utils/converter'

interface t_qrdoc_d {
  material: string
  materialname: string
  order: string
  qty: number
}
interface t_qrdoc {
  reqorder: string
  reqdate: string
  loc: string
  type: string
  qrcode: string
  order: string
  details: require_order[]
  selected: t_qrdoc_d[]
}
const db = useDbStore()
const showPicker = ref<boolean>(false)
const showDtPicker = ref<boolean>(false)
const currentDate = ref(['2023', '11', '01'])
const active = ref<number>(0)
const qrcode_str = ref<string>()
const qrdoc = ref<t_qrdoc>({
  reqorder: '',
  reqdate: '',
  type: '',
  qrcode: '',
  order: '',
  loc: '',
  details: [],
  selected: []
})
const locSelect = (o: any) => {
  qrdoc.value.loc = o.selectedOptions[0].text
  showPicker.value = false
}
const reqDtSelect = (o: any) => {
  qrdoc.value.reqdate = o.selectedValues[0] + '-' + o.selectedValues[1] + '-' + o.selectedValues[2]
  showDtPicker.value = false
}
const clearQrDoc = () => {
  qrdoc.value = {
    reqorder: '',
    reqdate: '',
    loc: '',
    type: '',
    qrcode: '',
    order: '',
    details: [],
    selected: []
  }
}
const onSearch = () => {
  const type = get_code_prefix(qrcode_str.value!)
  qrdoc.value.type = type
  qrdoc.value.qrcode = qrcode_str.value!
  const content = trimPrefix(qrcode_str.value!)
  qrdoc.value.reqorder = content
  qrcode_str.value = ''
  switch (e_code_prefix[type as keyof typeof e_code_prefix]) {
    case e_code_prefix.委外备料:
    case e_code_prefix.材料出库:
    case e_code_prefix.销售出库:
    case e_code_prefix.调出订单:
      searchInRequire(content)
      break
  }
}
const trimPrefix = (str: string) => {
  const indexOf = str.indexOf('#')
  return str.substring(indexOf + 1, str.length)
}

const searchInRequire = (key: string) => {
  const docs = db.require_order.filter(
    (r) => r.order_bill === key && (r.status === e_require_order_status.未发料 || r.status === e_require_order_status.部分发料)
  )
  if (docs.length === 0) {
    showDialog({ title: '错误', message: '找不到单据' })
    return
  }
  fill_ref_info(docs, require_order_define).then(() => {
    qrdoc.value.order = docs[0].order_bill
    qrdoc.value.details = docs
  })
}
const add_item = (order: require_order) => {
  if (qrdoc.value.selected.find((r) => r.order === order.billcode)) {
    showDialog({ title: '错误', message: '不要重复添加' })
    return
  }
  qrdoc.value.selected.push({
    material: typeof order.material === 'string' ? order.material : order.material.code,
    materialname: typeof order.material === 'string' ? order.material : order.material.name,
    order: order.billcode,
    qty: order.order_qty - order.called_qty
  })
}
const sum_item = () => {
  const items: { material: string; materialname: string; qty: number }[] = []
  qrdoc.value.selected.forEach((r) => {
    const exists = items.find((s) => s.material === r.material)
    if (exists) exists.qty += r.qty
    else {
      items.push({ material: r.material, materialname: r.materialname, qty: r.qty })
    }
  })
  return items
}
const submit = () => {
  if (qrdoc.value.loc === '' || qrdoc.value.reqdate === '') {
    showDialog({ title: '提示', message: '确定送料位置和时间' })
    return
  }
  const d = qrdoc.value.selected.map((r) => {
    return { require_code: r.order, qty: r.qty }
  })
  const a = { reqorder: qrdoc.value.reqorder, reqdate: qrdoc.value.reqdate, b: make_billcode('PB'), loc: qrdoc.value.loc, d: d }
  const result = require_to_mtlcall(a)
  const db = useDbStore()
  result.forEach((r) => {
    db.addMtlCall(r)
    const t = db.require_order.find((s) => s.billcode === r.srcbill)!
    t.called_qty += r.call_qty
  })
  db.saveRequireOrder()
  showDialog({ title: '提示', message: '操作成功' })
  clearQrDoc()
}
</script>
